import { getPubKey as getUserPubKey } from '@/api/user'
import { getPubKey, setPubKey } from './getPubKey'
import JSEncrypt from 'jsencrypt'

export default async function encrypt(val) {
  let pubk = getPubKey()
  try {
    if (!pubk || pubk === 'undefined') {
      const res = await getUserPubKey()
      pubk = res.data.pubKey
      pubk = pubk.replace(/\. +/g, '')
      pubk = pubk.replace(/[\r\n]/g, '')
      setPubKey(pubk)
    }
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(pubk)
    return encrypt.encrypt(val)
  } catch (error) {
    console.log(error)
  }
}
